package cn.monkey.family.server.domain.uc.auth.token;

import cn.monkey.family.data.context.RequestContext;
import cn.monkey.family.data.uc.auth.UserSession;
import jakarta.annotation.Nullable;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.io.Serializable;

public class RequestContextSerializer implements RedisSerializer<RequestContextSerializer.SerializableRequestContext> {

    private final GenericJackson2JsonRedisSerializer delegate;

    public static class SerializableRequestContext implements RequestContext, Serializable {
        private String orgId;
        private String platformId;
        private String traceId;
        private String token;

        @Nullable
        @Override
        public UserSession getUserSession() {
            return null;
        }

        @Override
        public String getOrgId() {
            return this.orgId;
        }

        @Override
        public String getPlatformId() {
            return this.platformId;
        }

        @Override
        public String getTraceId() {
            return this.traceId;
        }

        @Override
        public String getToken() {
            return this.token;
        }

        public void setOrgId(String orgId) {
            this.orgId = orgId;
        }

        public void setPlatformId(String platformId) {
            this.platformId = platformId;
        }

        public void setTraceId(String traceId) {
            this.traceId = traceId;
        }

        public void setToken(String token) {
            this.token = token;
        }
    }

    public RequestContextSerializer() {
        this(new GenericJackson2JsonRedisSerializer());
    }

    static SerializableRequestContext from(RequestContext requestContext) {
        SerializableRequestContext serializableRequestContext = new SerializableRequestContext();
        serializableRequestContext.setOrgId(requestContext.getOrgId());
        serializableRequestContext.setPlatformId(requestContext.getPlatformId());
        serializableRequestContext.setTraceId(requestContext.getTraceId());
        serializableRequestContext.setToken(requestContext.getToken());
        return serializableRequestContext;
    }

    public RequestContextSerializer(GenericJackson2JsonRedisSerializer delegate) {
        this.delegate = delegate;
    }

    @Override
    public byte[] serialize(SerializableRequestContext value) throws SerializationException {
        return this.delegate.serialize(from(value));
    }

    @Override
    public SerializableRequestContext deserialize(byte[] bytes) throws SerializationException {
        return this.delegate.deserialize(bytes, SerializableRequestContext.class);
    }

}
